package com.ruoyi.system.service.impl;

import java.util.*;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.bean.BeanValidators;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.domain.PDealer;
import com.ruoyi.system.domain.PDealerSchool;
import com.ruoyi.system.domain.PFileInfo;
import com.ruoyi.system.domain.vo.PSchoolVo;
import com.ruoyi.system.mapper.PDealerMapper;
import com.ruoyi.system.mapper.PDealerSchoolMapper;
import com.ruoyi.system.mapper.PFileInfoMapper;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.PSchoolMapper;
import com.ruoyi.system.domain.PSchool;
import com.ruoyi.system.service.IPSchoolService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;

/**
 * 学校Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-01-28
 */
@Service
public class PSchoolServiceImpl implements IPSchoolService 
{
    private static final Logger log = LoggerFactory.getLogger(PSchoolServiceImpl.class);
    @Autowired
    private PSchoolMapper pSchoolMapper;
    @Autowired
    private PDealerMapper dealerMapper;
    @Autowired
    private PDealerSchoolMapper pDealerSchoolMapper;
    @Autowired
    protected Validator validator;
    @Autowired
    private PFileInfoMapper pFileInfoMapper;

    /**
     * 查询学校
     * 
     * @param id 学校主键
     * @return 学校
     */
    @Override
    public PSchoolVo selectPSchoolById(Long id)
    {
        return pSchoolMapper.selectPSchoolVoById(id);
    }

    /**
     * 查询学校列表
     * 
     * @param pSchool 学校
     * @return 学校
     */
    @Override
    public List<PSchoolVo> selectPSchoolList(PSchool pSchool)
    {
        return pSchoolMapper.selectPSchoolVoList(pSchool);
    }

    /**
     * 新增学校
     * 
     * @param pSchool 学校
     * @return 结果
     */
    @Override
    public int insertPSchool(PSchool pSchool)
    {
        pSchool.setCreateTime(DateUtils.getNowDate());
        return pSchoolMapper.insertPSchool(pSchool);
    }
    /**
     * 新增学校
     *
     * @param pSchool 学校
     * @return 结果
     */
    @Override
    @Transactional
    public int insertPSchool(PSchoolVo pSchool) throws Exception {
        PSchool con = new PSchool();
        con.setSchoolName(pSchool.getSchoolName());
        con.setDelFlag("0");
        List<PSchool> schoolList = pSchoolMapper.selectPSchoolList(con);
        if (schoolList != null && schoolList.size() >= 1){
            throw new Exception("该学校名称已经存在，不允许重复的学校名称");
        }
        Long dealerId = pSchool.getDealerId();
        if(dealerId != null){
            PDealer pDealer = dealerMapper.selectPDealerById(dealerId);
            if(pDealer == null){
                throw new RuntimeException("分销商不存在");
            }
            int num = pSchoolMapper.insertPSchool(pSchool);
            //添加学校分销商关联
            PDealerSchool pDealerSchool = new PDealerSchool();
            pDealerSchool.setDealerId(dealerId);
            pDealerSchool.setSchoolId(pSchool.getId());
            pDealerSchoolMapper.insertPDealerSchool(pDealerSchool);
            PFileInfo pFileInfo = pFileInfoMapper.selectPFileInfoById(pSchool.getFileId());
            if (pFileInfo!=null){
                pFileInfo.setContactId(pSchool.getId());
                pFileInfo.setContactTable("p_school");
                pFileInfoMapper.updatePFileInfo(pFileInfo);
            }
            return num;
        }
        return 0;
    }

    @Override
    public int updatePSchool(PSchool pSchool) throws Exception {
        return 0;
    }

    /**
     * 新增学校
     *
     * @param pDealerSchool 学校
     * @return 结果
     */
    @Override
    public int signPSchool(PDealerSchool pDealerSchool)
    {

        int num = 0;
        Long dealerId = pDealerSchool.getDealerId();
        if(dealerId == null){
            PDealer pDealer = dealerMapper.selectPDealerById(dealerId);
            if(pDealer == null){
                throw new RuntimeException("分销商不存在");
            }
            PDealerSchool record = new PDealerSchool();
            record.setSchoolId(pDealerSchool.getSchoolId());
            List<PDealerSchool> list = pDealerSchoolMapper.selectPDealerSchoolList(record);
            if(list.isEmpty()){
                num = pDealerSchoolMapper.insertPDealerSchool(pDealerSchool);
                return num;
            }
            record = list.get(0);
            //重新签约分销商
            record.setDealerId(dealerId);
            num = pDealerSchoolMapper.updatePDealerSchool(record);
            return num;
        }
        return num;
    }

    @Transactional
    @Override
    public String importSchool(List<PSchoolVo> schoolVoList, boolean isUpdateSupport) {
        if (StringUtils.isNull(schoolVoList) || schoolVoList.size() == 0)
        {
            throw new ServiceException("导入学校数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (PSchoolVo school : schoolVoList)
        {
            try
            {
                // 验证是否存在这个学校
                BeanValidators.validateWithException(validator, school);
                PSchool s = pSchoolMapper.selectSchoolBySchoolName(school.getSchoolName());
                PDealer con = new PDealer();
                con.setDealerName(school.getDealerName());
                List<PDealer> pDealerList = dealerMapper.selectPDealerList(con);
                if (pDealerList == null || pDealerList.size()<1){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、学校 " + school.getSchoolName() + " 填写的经销商不存在！");
                }
                else if (StringUtils.isNull(s))
                {
                    school.setDelFlag("0");
                    school.setOrderNum(0);
                    school.setCreateTime(DateUtils.getNowDate());
                    school.setCreateBy(SecurityUtils.getUsername());
                    school.setUpdateBy(SecurityUtils.getUsername());
                    school.setUpdateTime(DateUtils.getNowDate());
                    pSchoolMapper.insertPSchool(school);
                    //添加学校分销商关联
                    PDealerSchool pDealerSchool = new PDealerSchool();
                    pDealerSchool.setDealerId(pDealerList.get(0).getId());
                    pDealerSchool.setSchoolId(school.getId());
                    pDealerSchoolMapper.insertPDealerSchool(pDealerSchool);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学校 " + school.getSchoolName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {

                    school.setId(s.getId());
                    school.setUpdateBy(SecurityUtils.getUsername());
                    school.setUpdateTime(DateUtils.getNowDate());
                    pSchoolMapper.updatePSchool(school);
                    PDealerSchool pDealerSchool = new PDealerSchool();
                    pDealerSchool.setSchoolId(school.getId());
                    List<PDealerSchool> pDealerSchools = pDealerSchoolMapper.selectPDealerSchoolList(pDealerSchool);

                    if (pDealerSchools != null && pDealerSchools.size() >=1){
                        pDealerSchool = pDealerSchools.get(0);
                        pDealerSchool.setDealerId(pDealerList.get(0).getId());
                        pDealerSchoolMapper.updatePDealerSchool(pDealerSchool);
                    }else {
                        pDealerSchool.setDealerId(pDealerList.get(0).getId());
                        pDealerSchoolMapper.insertPDealerSchool(pDealerSchool);
                    }
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学校 " + school.getSchoolName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、学校 " + school.getSchoolName() + " 已存在");
                }
            }
            catch (ConstraintViolationException ec
            ){
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + school.getSchoolName() + " 导入失败：";
                failureMsg.append(msg + ec.getMessage());
//                log.error(msg, ec);
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + school.getSchoolName() + " 导入失败：";
                failureMsg.append("系统异常，请联系管理员！");
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    /**
     * 修改学校
     * 
     * @param pSchool 学校
     * @return 结果
     */
    @Override
    public int updatePSchool(PSchoolVo pSchool) throws Exception {

        PSchool con = new PSchool();
        con.setSchoolName(pSchool.getSchoolName());
        con.setDelFlag("0");
        List<PSchool> schoolList = pSchoolMapper.selectPSchoolList(con);
        if (schoolList != null && schoolList.size() >= 1 && schoolList.get(0).getId() != pSchool.getId()) {
            throw new Exception("该学校名称已经存在，不允许重复的学校名称");
        }
        Long dealerId = pSchool.getDealerId();
        if(dealerId != null) {
            PDealer pDealer = dealerMapper.selectPDealerById(dealerId);
            if(pDealer == null){
                throw new RuntimeException("分销商不存在");
            }
            //修改关联经销商
            PDealerSchool pDealerSchool = new PDealerSchool();
            pDealerSchool.setSchoolId(pSchool.getId());
            List<PDealerSchool> pDealerSchools = pDealerSchoolMapper.selectPDealerSchoolList(pDealerSchool);

            if (pDealerSchools != null && pDealerSchools.size() >=1){
                pDealerSchool = pDealerSchools.get(0);
                pDealerSchool.setDealerId(dealerId);
                pDealerSchoolMapper.updatePDealerSchool(pDealerSchool);
            }else {
                pDealerSchoolMapper.deletePDealerSchoolById(pDealerSchool.getId());
                pDealerSchool.setDealerId(dealerId);
                pDealerSchoolMapper.insertPDealerSchool(pDealerSchool);
            }
            PFileInfo confile = new PFileInfo();
            confile.setContactId(pSchool.getId());
            confile.setContactTable("p_school");
            confile.setDelFlag("0");
            List<PFileInfo> pFileInfos = pFileInfoMapper.selectPFileInfoList(confile);
            if (!CollectionUtils.isEmpty(pFileInfos)&& pFileInfos.get(0).getId() != pSchool.getFileId()){
                PFileInfo pFileInfo = pFileInfos.get(0);
                pFileInfo.setDelFlag("1");
                pFileInfoMapper.updatePFileInfo(pFileInfo);
                pFileInfo = pFileInfoMapper.selectPFileInfoById(pSchool.getFileId());
                pFileInfo.setContactId(pSchool.getId());
                pFileInfo.setContactTable("p_school");
                pFileInfoMapper.updatePFileInfo(pFileInfo);
            }else if(CollectionUtils.isEmpty(pFileInfos)){
                PFileInfo  pFileInfo = pFileInfoMapper.selectPFileInfoById(pSchool.getFileId());
                pFileInfo.setContactId(pSchool.getId());
                pFileInfo.setContactTable("p_school");
                pFileInfo.setDelFlag("0");
                pFileInfoMapper.updatePFileInfo(pFileInfo);
            }
            pSchool.setUpdateTime(DateUtils.getNowDate());
            return pSchoolMapper.updatePSchool(pSchool);
        }
        return 0;
    }

    /**
     * 批量删除学校
     * 
     * @param ids 需要删除的学校主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deletePSchoolByIds(Long[] ids)
    {
//        int i = pSchoolMapper.deletePSchoolByIds(ids);
        for (int i = 0; i<ids.length;i++){
            PSchool pSchool = new PSchool();
            pSchool.setDelFlag("1");
            pSchool.setId(ids[i]);
            pSchoolMapper.updatePSchool(pSchool);
            PFileInfo pFileInfo = pFileInfoMapper.selectPFileInfoById(ids[i]);
            pFileInfo.setDelFlag("1");
            pFileInfoMapper.updatePFileInfo(pFileInfo);
        }
        pDealerSchoolMapper.deletePDealerSchoolBySchoolIds(ids);
        return ids.length;
    }

    /**
     * 删除学校信息
     * 
     * @param id 学校主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deletePSchoolById(Long id)
    {
        PSchool pSchool = new PSchool();
        pSchool.setDelFlag("1");
        pSchool.setId(id);
        pSchoolMapper.updatePSchool(pSchool);
        pDealerSchoolMapper.deletePDealerSchoolBySchoolIds(new Long[]{id});
        return 1;
    }
}
